package com.sanxiang.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sanxiang.common.CommonResult;
import com.sanxiang.entity.EnterpriseTable;
import com.sanxiang.entity.OrderTable;
import com.sanxiang.entity.UserTable;
import com.sanxiang.entity.UserUpdate;
import com.sanxiang.mapper.EnterpriseTableMapper;
import com.sanxiang.mapper.OrderTableMapper;
import com.sanxiang.mapper.UserTableMapper;
import com.sanxiang.service.FileService;
import com.sanxiang.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserTableMapper userTableMapper;
    @Resource
    private EnterpriseTableMapper enterpriseTableMapper;
    @Resource
    private OrderTableMapper orderTableMapper;
    @Resource
    private UserService userService;
    @Resource
    private FileService fileService;

    @PostMapping("/applyorder")
    public CommonResult ApplyOrder(UserTable userTable, @RequestParam String enterpriseName) {
        // 1.用户表操作
        // 通过身份证号查询判断客户是否存在
        QueryWrapper<UserTable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_idcard", userTable.getUserIdcard());
        UserTable user = userTableMapper.selectOne(queryWrapper);
        // 客户存在则更新信息、客户不存在则新增信息
        Integer user_id;
        String return_;
        if (user == null) {
            userTableMapper.insert(userTable);
            return_ = "用户为未注册客户，信息录入完成";
            user_id = userTable.getUserId();
        } else {
            // 数据库存在改客户，更新客户信息
            UpdateWrapper<UserTable> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_idcard", userTable.getUserIdcard());
            userTableMapper.update(userTable, updateWrapper);
            return_ = "用户为已注册客户，信息更新完成";
            user_id = user.getUserId();
        }
        //2、企业表操作
        // 通过查询企业名称，判断企业是否存在
        QueryWrapper<EnterpriseTable> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("enterprise_name", enterpriseName);
        EnterpriseTable enterpriseTable = enterpriseTableMapper.selectOne(queryWrapper2);
        if (enterpriseTable == null) {
            // 不存在则新增企业
            EnterpriseTable enterpriseTable1 = new EnterpriseTable();
            enterpriseTable1.setEnterpriseName(enterpriseName);
            enterpriseTable1.setEnterpriseLegalPersonId(user_id);
            enterpriseTableMapper.insert(enterpriseTable1);
            return_ += "，企业为未录入企业，新增企业信息完毕";
        } else {
            // 存在则修改企业法人代表
            enterpriseTable.setEnterpriseLegalPersonId(user_id);
            enterpriseTableMapper.update(enterpriseTable, queryWrapper2);
            return_ += "，企业为已录入企业，更新企业法人信息完毕";
        }
        // 新建订单
        OrderTable orderTable = new OrderTable();
        orderTable.setOrderUserId(user_id);
//        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
        Date date = new Date(System.currentTimeMillis());
        orderTable.setOrderCreatTime(date);
        orderTable.setOrderUpdateTime(date);
        orderTableMapper.insert(orderTable);
        return_ += ",订单创建完成";
        Map<String, Object> return_map = new HashMap<>();
        return_map.put("userId", user_id);
        return_map.put("orderId", orderTable.getOrderId());
        return_map.put("explain", return_);
        return CommonResult.success(return_map);
    }

    @PostMapping("/updateUser")
    public CommonResult<UserTable> updateUser(UserUpdate userUpdate, @RequestParam MultipartFile file) throws ParseException {
        String Fname = "";
        //判断文件是否为空，不为空则保存文件到本地并返回文件名信息，为空则返回错误信息
        if (!file.isEmpty()) {
            try {
                //上传成功返回文件名信息，上传失败返回错误信息
                Fname = fileService.Save_File(file);
            } catch (RuntimeException e) {
                CommonResult.failed(Fname);
            }
        } else {
            CommonResult.failed("文件为空");
        }
        //更新完成后，返回更新后的用户表结果
        Integer user_id = userService.UpdateUserTableByOrderId(userUpdate, Fname);
        UserTable userTable = userService.selectByUserId(user_id);
        return CommonResult.success(userTable);
    }


}
